package tcts0421;

import java.util.Arrays;
public class Main {
    public static void main(String[]args) {
        int[] nums = {2,1,-2,3};
        System.out.println(threeSumClosest(nums, 5));
    }
    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);	//排序
        int numberSum = nums[0] + nums[1] + nums[2];//最接近的和
        for(int i=0;i<nums.length;i++) {
            int flag = nums[i];
            int start = i+1;//开头指针
            int end = nums.length-1;//末尾指针
            while(start < end) {
                int sum = (flag + nums[start] + nums[end]);//三数之和
                if(Math.abs(sum - target) < Math.abs(numberSum - target)) {
                    numberSum = sum;
                }
                if(sum > target) {
                    end--;
                }else if(sum < target) {
                    start++;
                }else {
                    return numberSum;
                }
            }
        }
        return numberSum;
    }
}
